package com.cheung.leetcode.day;

import lyroot.entity.ListNode;

/**
 * @BelongsProject : java-leetcode
 * @BelongsPackage : com.cheung.leetcode.day
 * @Author :  cheungming
 * @CreateTime : 2024-07-04 14:08:36
 * @Description : 每日 一题
 * @Version : 1.0
 */
public class Code2Test {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // 创建一个结果链表
        ListNode result = new ListNode(0);
        // 创建一个指针,保持每一步运算的指针
        ListNode pointer = result;
        int carry = 0;
        while (l1 != null || l2 != null) {
            // 获取两个链表的值
            int x = l1 != null ? l1.val : 0;
            int y = l2 != null ? l2.val : 0;
            int sum = x + y + carry;

            ListNode node = new ListNode(sum % 10);
            carry = sum / 10;

            pointer.next = node;
            pointer = pointer.next;

            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }

        if (carry > 0) {
            pointer.next = new ListNode(carry);
        }

        return result.next;
    }

}
